import { defineStore } from 'pinia'
import { farmerApi } from '@/api'

export const useCategoryStore = defineStore('category', {
  state: () => ({
    categoryList: [],
    currentCategory: null,
    goodsList: [],
    loading: false
  }),
  
  getters: {
    getCategoryList: (state) => state.categoryList,
    getCurrentCategory: (state) => state.currentCategory,
    getGoodsList: (state) => state.goodsList,
    getLoading: (state) => state.loading
  },
  
  actions: {
    // 设置分类列表
    setCategoryList(list) {
      this.categoryList = list
    },
    
    // 设置当前分类
    setCurrentCategory(category) {
      this.currentCategory = category
    },
    
    // 设置商品列表
    setGoodsList(list) {
      this.goodsList = list
    },
    
    // 设置加载状态
    setLoading(status) {
      this.loading = status
    },
    
    // 获取分类列表
    async fetchCategoryList() {
      try {
        this.setLoading(true)
        const result = await farmerApi.getCategoryList()
        this.setCategoryList(result)
        return result
      } catch (error) {
        console.error('获取分类列表失败:', error)
        uni.showToast({
          title: '获取分类列表失败',
          icon: 'none'
        })
      } finally {
        this.setLoading(false)
      }
    },
    
    // 根据分类ID获取商品列表
    async fetchGoodsList(categoryId) {
      try {
        this.setLoading(true)
        const result = await farmerApi.getGoodsListByCategoryId({ categoryId })
        this.setGoodsList(result)
        return result
      } catch (error) {
        console.error('获取商品列表失败:', error)
        uni.showToast({
          title: '获取商品列表失败',
          icon: 'none'
        })
      } finally {
        this.setLoading(false)
      }
    }
  }
}) 